package com.atguigu.juc.day04.cf;

import com.atguigu.juc.day04.pool.Demo01MyPool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class Demo04AsyncTaskWithResult {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 1、获取线程池对象
        ExecutorService executorService = Demo01MyPool.getExecutorService();

        // 2、封装一个有返回值的任务
        Supplier<String> supplier = ()->{
            try {
                System.out.println(Thread.currentThread().getName() + " 开始睡觉。");
                TimeUnit.SECONDS.sleep(10);
                System.out.println(Thread.currentThread().getName() + " 结束睡觉。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "task result";
        };

        // 3、把任务对象传给 CompletableFuture 的 supplyAsync() 方法
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(supplier, executorService);

        // 4、获取目标任务的返回值
        // ※get() 方法会一直阻塞，直到目标任务方法返回
        String taskResult = completableFuture.get();
        System.out.println("taskResult = " + taskResult);

    }

}
